package com.audaque.springboot.foshanupload.core.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author zgb
 * @desc ...
 * @date 2023-03-01 20:13:18
 */
public class OnlyDateUtils {


    /**
     * 时间戳转日期
     *
     * @param timeStamp
     * @return
     */
    public static Date getDate(long timeStamp) {
        return new Date(timeStamp);
    }


    /**
     * 获取年份
     */
    public static int getYear(Date date) {
        int year = date.getYear() + 1900;
        return year;
    }

    /**
     * 获取月份
     */
    public static int getMonth(Date date) {
        int month = date.getMonth() + 1;
        return month;
    }


    /**
     * 获取两日期相差的天数
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static Integer getDiffDays(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return 0;
        }
        return (int) ((endDate.getTime() - startDate.getTime()) / (1000 * 3600 * 24));
    }

    /**
     * @Description: 计算两个日期相隔多少天
     * @Param: [start, end]
     * @return: int
     */
    public static int daysApart(Date start, Date end) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date StartDate = df.parse(df.format(start));
            Date endDate = df.parse(df.format(end));
            return (int) ((endDate.getTime() - StartDate.getTime()) / (24 * 60 * 60 * 1000L));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 获取两日期相差的天数(格式转为YMD格式 消除HMS带来的误差)
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static Integer getDiffDaysEx(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return 0;
        }
        try {
            DateFormat df = DateFormatUtil.DATE_FORMATTER.get();
            startDate = df.parse(df.format(startDate));
            endDate = df.parse(df.format(endDate));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (int) ((endDate.getTime() - startDate.getTime()) / (1000 * 3600 * 24)) + 1;
    }


    /**
     * 给日期加上小时
     *
     * @param date yyyy-MM-dd格式的日期
     * @param hour
     * @return
     */
    public static Date addHour(Date date, int hour) {
        //当前日期毫秒数
        long currentTime = date.getTime();
        //计算小时总计的毫秒数
        long hourTime = hour * 60 * 60 * 1000;
        //总的毫秒数
        long totalTime = currentTime + hourTime;
        return new Date(totalTime);
    }


    /**
     * 判断两个日期区间是否存在交叉
     *
     * @param firstBeginDate
     * @param firstEndDate
     * @param secondBeginDate
     * @param secondEndDate
     * @return 如果有交叉返回true  否则返回false
     */
    public static boolean checkDateRangeCross(Date firstBeginDate, Date firstEndDate, Date secondBeginDate, Date secondEndDate) {
        return ((firstBeginDate.getTime() >= secondBeginDate.getTime())
                && firstBeginDate.getTime() < secondEndDate.getTime())
                ||
                ((firstBeginDate.getTime() > secondBeginDate.getTime())
                        && firstBeginDate.getTime() <= secondEndDate.getTime())
                ||
                ((secondBeginDate.getTime() >= firstBeginDate.getTime())
                        && secondBeginDate.getTime() < firstEndDate.getTime())
                ||
                ((secondBeginDate.getTime() > firstBeginDate.getTime())
                        && secondBeginDate.getTime() <= firstEndDate.getTime());
    }

    /**
     * 判断两个日期区间是否存在交叉
     *
     * @param firstBeginDate
     * @param firstEndDate
     * @param secondBeginDate
     * @param secondEndDate
     * @return 如果有交叉返回true  否则返回false
     */
    public static boolean checkDateRangeCross(long firstBeginDate, long firstEndDate, long secondBeginDate, long secondEndDate) {
        return ((firstBeginDate >= secondBeginDate)
                && firstBeginDate < secondEndDate)
                ||
                ((firstBeginDate > secondBeginDate)
                        && firstBeginDate <= secondEndDate)
                ||
                ((secondBeginDate >= firstBeginDate)
                        && secondBeginDate < firstEndDate)
                ||
                ((secondBeginDate > firstBeginDate)
                        && secondBeginDate <= firstEndDate);
    }


    /**
     * 获得两个日期之间的所有日期
     *
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    private static List<Date> dateSplit(Date startDate, Date endDate) throws Exception {
        if (!startDate.before(endDate)) {
            throw new Exception("开始时间应该在结束时间之后");
        }
        Long spi = endDate.getTime() - startDate.getTime();
        Long step = spi / (24 * 60 * 60 * 1000);// 相隔天数
        List<Date> dateList = new ArrayList<Date>();
        dateList.add(endDate);
        for (int i = 1; i <= step; i++) {
            dateList.add(new Date(dateList.get(i - 1).getTime()
                    - (24 * 60 * 60 * 1000)));// 比上一天减一
        }
        return dateList;
    }


    /**
     * 得到对应星期的系数  星期日：1，星期一：2，星期二：3，星期三：4，星期四：5，星期五：6，星期六：7
     *
     * @param weekDays 星期格式  星期一|星期二
     */
    public static String weekForNum(String weekDays) {
        //返回结果为组合的星期系数
        String weekNumber = "";
        //解析传入的星期
        if (weekDays.indexOf("|") != -1) {//多个星期数
            String[] strWeeks = weekDays.split("\\|");
            for (int i = 0; i < strWeeks.length; i++) {
                weekNumber = weekNumber + "" + getWeekNum(strWeeks[i]).toString();
            }
        } else {//一个星期数
            weekNumber = getWeekNum(weekDays).toString();
        }
        return weekNumber;
    }

    /**
     * 将星期转换为对应的系数  星期日：1，星期一：2，星期二：3，星期三：4，星期四：5，星期五：6，星期六：7
     *
     * @param strWeek
     * @return
     */
    public static Integer getWeekNum(String strWeek) {
        Integer number = 1;//默认为星期日
        if ("星期日".equals(strWeek)) {
            number = 1;
        } else if ("星期一".equals(strWeek)) {
            number = 2;
        } else if ("星期二".equals(strWeek)) {
            number = 3;
        } else if ("星期三".equals(strWeek)) {
            number = 4;
        } else if ("星期四".equals(strWeek)) {
            number = 5;
        } else if ("星期五".equals(strWeek)) {
            number = 6;
        } else if ("星期六".equals(strWeek)) {
            number = 7;
        }
        return number;
    }


    /**
     * @Description: yyyyMMddHHmmss字符串转化为日期
     * @Param: [time]
     * @return: java.util.Date
     * @Author: cx
     * @Date: 2018/5/17
     */
    public static Date getStringTimeToDate(String time, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


    /**
     * 获取格式 年-月-日  上午/下午
     *
     * @param date
     * @return
     */
    public static String getDateWU(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a");
        String format = sdf.format(new Date());
        return format;
    }


    /**
     * 格式化时间
     *
     * @param source
     * @return
     */
    public static final String formatDate(Date source) {
        return formatDate(source, null);
    }

    /**
     * 格式化时间
     *
     * @param source
     * @param format
     * @return
     */
    public static final String formatDate(Date source, String format) {
        if (source == null) {
            return "";
        }
        DateFormat dateFormat = null;
        if (StringUtils.isEmpty(format)) {
            dateFormat = new SimpleDateFormat(DateFormatUtil.DATE_TIME_FORMAT);
        } else {
            dateFormat = new SimpleDateFormat(format);
        }
        return dateFormat.format(source);
    }

    /**
     * 解析日期字符串.默认个格式
     *
     * @param source
     * @return
     */
    public static final Date parseDateStr(String source) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        DateFormat dateFormat = new SimpleDateFormat(DateFormatUtil.DATE_TIME_FORMAT);
        try {
            return dateFormat.parse(source);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 解析时间字符串：默认是按照yyyy-MM-dd HH:mm:ss解析
     *
     * @param source
     * @param format
     * @return
     */
    public static final Date parseDateStr(String source, String format) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        DateFormat dateFormat = null;
        if (StringUtils.isEmpty(format)) {
            dateFormat = new SimpleDateFormat(DateFormatUtil.DATE_TIME_FORMAT);
        } else {
            dateFormat = new SimpleDateFormat(format);
        }
        try {
            return dateFormat.parse(source);
        } catch (ParseException e) {
            return null;
        }
    }


    public static String taobaoOrderRedisKey(Date date, String orderNo) {
        String formatDate = formatDate(date, "yyyyMM");
        String formatDate2 = formatDate(date, DateFormatUtil.DATE_PATTERN_YYYYMMDD);
        return "taobaoorder" + formatDate + ":" + formatDate2 + ":" + orderNo;
    }

    public static String userOrderRedisKey(Date date, String orderNo) {
        String formatDate = formatDate(date, "yyyyMM");
        String formatDate2 = formatDate(date, DateFormatUtil.DATE_PATTERN_YYYYMMDD);
        return "userorder" + formatDate + ":" + formatDate2 + ":" + orderNo;
    }


    public static boolean isThisTime(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(date);// 参数时间
        String now = sdf.format(new Date());// 当前时间
        if (param.equals(now)) {
            return true;
        }
        return false;
    }


    /**
     * 获取新人红包的时间大小
     *
     * @param beferDate
     * @return
     * @throws ParseException
     */
    public static boolean getMaxDate(Date beferDate) throws ParseException {
        String string = CalendarUtils.getDayBeforeOrAfter(beferDate, 183);
        Date date1 = new SimpleDateFormat(DateFormatUtil.DATE_TIME_FORMAT).parse(string);
        Date date2 = new Date();
        return (date2.compareTo(date1)) == 1 ? false : true;

    }


    /**
     * 获取当前秒数:从 1970年至今
     *
     * @return
     */
    public static int getTimeSeconds() {
        long timeMillis = System.currentTimeMillis();
        long timeSeconds = timeMillis / 1000;
        return (int) timeSeconds;
    }

    /**
     * 获取当前时间搓
     *
     * @return
     */
    public static long getTimestamp() {
        return new Date().getTime();
    }

    public static long getTimestamp(String date) {
        try {
            if ("[]".equals(date)) {
                return getTimestamp();
            }
            DateFormat df = new SimpleDateFormat(DateFormatUtil.DATE_TIME_FORMAT);
            Date dt1 = df.parse(date);
            return dt1.getTime();
        } catch (ParseException e) {
        }
        return getTimestamp();
    }

    public static String getTimes(Long timesTamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateFormatUtil.DATE_TIME_FORMAT);
        Date date = new Date(timesTamp);
        String res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * 根据生日获取年龄
     *
     * @param
     * @return
     */
    public static int getAgeByBirth(Date birthDay) {
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            } else {
                age--;
            }
        }
        return age;
    }

    /**
     * 返回当前年月日 时分秒
     *
     * @return
     */
    public static String getTime() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }

    /**
     * 根据固定的格式，将字符串转化为Date
     *
     * @param str
     * @param ftm
     * @return
     */
    public static Date parseDate(String str, String ftm) {
        if (str == null) {
            return null;
        }
        try {
            return new SimpleDateFormat(ftm).parse(str);
        } catch (ParseException e) {
            return null;
        }

    }

    /**
     * 获取过去的天数
     *
     * @param date
     * @return
     */
    public static long pastDays(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (24 * 60 * 60 * 1000);
    }

    /**
     * 获取过去的小时
     *
     * @param date
     * @return
     */
    public static long pastHour(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (60 * 60 * 1000);
    }

    /**
     * 获取过去的分钟
     *
     * @param date
     * @return
     */
    public static long pastMinutes(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (60 * 1000);
    }

    /**
     * 转换为时间（天,时:分:秒.毫秒）
     *
     * @param timeMillis
     * @return
     */
    public static String formatDateTime(long timeMillis) {
        long day = timeMillis / (24 * 60 * 60 * 1000);
        long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
        long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
        return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
    }

    /**
     * 获取两个日期之间的天数，Date类型
     *
     * @param before
     * @param after
     * @return
     */
    public static double getDistanceOfTwoDate(Date before, Date after) {
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
    }

    /**
     * 获取两个日期之间的天数，字符串格式
     *
     * @param before
     * @param after
     * @param fmt    : 字符串的日期格式
     * @return
     */
    public static double getDistanceOfTwoDate(String before, String after, String fmt) {
        Date beforeD = parseDate(before, fmt);
        Date afterD = parseDate(after, fmt);

        return getDistanceOfTwoDate(beforeD, afterD);
    }

    /**
     * @param before
     * @param after
     * @return
     * @Description: 获取两个日期之间的小时数
     */
    public static double getDistHoursOfTwoDate(Date before, Date after) {
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return (afterTime - beforeTime) / (1000 * 60 * 60);
    }

    /**
     * @param start
     * @param end
     * @return
     * @Description: 获取两个时间相差的分钟数
     */
    public static Integer diffMinute(Date start, Date end) {
        return (int) Math.ceil((double) (end.getTime() - start.getTime()) / (1000 * 60));
    }

    /**
     * 通过毫秒时间戳获取小时数和分钟数
     *
     * @param time
     * @return
     */
    public static String getHourAndMinute(long time) {
        int minute = (int) Math.ceil((double) (time) / (1000 * 60));
        int hours = (int) Math.floor((double) minute / 60);
        minute = minute % 60;
        StringBuilder sb = new StringBuilder();
        if (hours > 0) {
            sb.append(hours).append("小时");
        }
        if (minute > 0) {
            sb.append(minute).append("分");
        }
        return sb.toString();
    }

    //获取一天中的最早时间
    public static Date getBeginDate(Date date) {
        System.out.println("date:" + date);
        Calendar calendar = Calendar.getInstance();
        System.out.println("calendar:" + calendar);
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        date = calendar.getTime();
        System.out.println("date:" + date);
        return date;
    }

    //获取一天的最晚时间
    public static Date getEndDate(Date date) {
        System.out.println("date:" + date);
        Calendar calendar = Calendar.getInstance();
        System.out.println("calendar:" + calendar);
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        date = calendar.getTime();
        System.out.println("date:" + date);
        return date;
    }

}
